package com.wyz.socket.test.client;

import com.wyz.socket.core.base.Context;
import com.wyz.socket.core.base.packet.file.FileSendPacket;
import com.wyz.socket.core.impl.chain.AbstractCloseChain;
import com.wyz.socket.core.impl.ConnectorHandler;
import com.wyz.socket.core.impl.Connector;
import com.wyz.socket.core.impl.IoSelectorProvider;
import com.wyz.socket.core.impl.scheduler.SchedulerImpl;
import com.wyz.socket.core.impl.stealing.IoStealingSelectorProvider;
import com.wyz.socket.core.utils.FileUtils;
import com.wyz.socket.core.utils.Log;

import java.io.*;

public class Client {
    public static volatile boolean isClose = false;

    public static void main(String[] args) throws IOException {
        Context.setup()
                .setIoProvider(new IoStealingSelectorProvider(4))
                .setScheduler(new SchedulerImpl(1))
                .start();

        ServerInfo info = UDPSearcher.searchServer(10000);
        System.out.println("Server:" + info);
        if (info != null) {
            try (TCPClient tcpClient = TCPClient.startWith(info, FileUtils.getCacheDir("client"))) {
                if (tcpClient == null) {
                    return;
                }
                tcpClient.getCloseChain().addChain(new AbstractCloseChain() {
                    @Override
                    protected boolean consume(ConnectorHandler handler, Connector connector) {
                        Log.printlnInfo("Main CLose", "server close");
                        return true;
                    }
                });
                write(tcpClient);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                Context.close();
            }
        }
    }

    static BufferedReader input;

    private static void write(TCPClient tcpClient) {
        input = new BufferedReader(new InputStreamReader(System.in));
        try {
            do {
                // 键盘读取一行
                String str = null;
                try {
                    str = input.readLine();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (str == null || "00bye00".equalsIgnoreCase(str)) {
                    break;
                }
                if (str.length() == 0) continue;
                if (str.startsWith("--f")) {
                    String[] strings = str.split(" ");
                    if (strings.length >= 2) {
                        File file = new File(strings[1]);
                        if (file.exists() && file.isFile()) {
                            FileSendPacket packet = new FileSendPacket(file);
                            tcpClient.send(packet);
                            continue;
                        }
                    }
                }
                // 发送到服务器
                tcpClient.send(str);
            }
            while (!isClose);
        } catch (Throwable e) {

        }
    }
}
